package com.spider.im.chat.message;

import com.spider.im.chat.annotation.MessageTypeHandler;
import com.spider.im.chat.proto.ChatProto;
import com.spider.im.common.aspect.BusinessException;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
// 3. 创建上下文类来管理和调用相应的策略
@Component
public class MessageHandlerContext {

    private Map<ChatProto.MessageType, MessageStrategy<?>> strategyMap = new ConcurrentHashMap<>();

    @Autowired
    private ApplicationContext applicationContext;

    @PostConstruct
    public void init() {
        // 获取所有实现了MessageStrategy接口的bean
        Map<String, Object> beansOfType = applicationContext.getBeansWithAnnotation(MessageTypeHandler.class);
        for (Map.Entry<String, Object> entry : beansOfType.entrySet()) {
            Object bean = entry.getValue();
            if (bean instanceof MessageStrategy<?>) {
                MessageTypeHandler annotation = bean.getClass().getAnnotation(MessageTypeHandler.class);
                if (annotation != null) {
                    ChatProto.MessageType type = annotation.type();
                    strategyMap.put(type, (MessageStrategy<?>) bean);
                }
            }
        }
    }


    public MessageStrategy<?> getStrategy(ChatProto.MessageType type) {
        MessageStrategy<?> strategy = (MessageStrategy<?>) strategyMap.get(type);
        if (strategy != null) {
           return strategy;
        } else {
           log.error("No strategy found for type: {}", type);
           throw new BusinessException(500, "No strategy found for type: " + type);
        }
    }
}
